package com.lujianfei.powersearch.adapter

import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.base.MovableAdapter
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.databinding.AdapterSortItemBinding
import com.lujianfei.powersearch.utils.SpanUtils
import com.lujianfei.powersearch.utils.SystemUtils

class SortAdapter: MovableAdapter<SearchItemModel, SortAdapterViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SortAdapterViewHolder {
        return SortAdapterViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.adapter_sort_item, parent, false))
    }

    override fun onBindViewHolder(holder: SortAdapterViewHolder, position: Int) {
        holder.bind(datas[position])
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?) {
        viewHolder?.itemView?.setBackgroundColor(SystemUtils.getApplicationContext().getColor(R.color.top_bg))
    }

    override fun clearView(viewHolder: RecyclerView.ViewHolder?) {
        viewHolder?.itemView?.setBackgroundColor(SystemUtils.getApplicationContext().getColor(R.color.white))
    }
}

class SortAdapterViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    var binding: AdapterSortItemBinding?= null
    init {
        binding = AdapterSortItemBinding.bind(itemView)
    }
    fun bind(item:SearchItemModel) {
        binding?.showLevel = false
        binding?.model = item
        binding?.showPlay = item.imagePath?.contains("video")
        kotlin.runCatching {
            if (item.imagePath.isNullOrBlank()) {
                binding?.photo = null
            } else {
                val imagePathArr = item.imagePath?.split(",")
                if (imagePathArr.isNullOrEmpty()) {
                    binding?.showPlay = item.imagePath?.contains("video")
                    binding?.photo = Uri.parse(item.imagePath)
                } else {
                    imagePathArr.first().let { firstPath->
                        binding?.showPlay = firstPath.contains("video")
                        binding?.photo = Uri.parse(firstPath)
                    }
                }
            }
        }.onFailure {
            binding?.photo = null
        }
        binding?.executePendingBindings()
    }
}